import Message from "./Message.vue";
import { render, h } from "vue";
import { IMessageOptions, IMessage } from "@/interface/IUse";


// 虚拟节点
let instance: any = null;
const instances: Array<any> = [];

export const createMessage: IMessage = (options: IMessageOptions | string) => {
  const baseOptions: IMessageOptions = { content: '这是一条消息', lastTime: 2500, type: 'info' };
  if (typeof options === 'string') {
    options = {
      ...baseOptions,
      content: options,
      type: 'error'
    }
  } else {
    options = options ? options : baseOptions;
  }

  // 创建虚拟节点, h的第一个参数可以是标签名或者是一个vue组件
  instance = h(Message, options);

  const container = document.createElement('div');
  // 渲染真实节点
  render(instance, container);

  const component = instance.component;
  const props = component?.props;
  /**
   * 将组件中的seed初始化为当前instances的长度
   * 例如当前的instance为['message1', 'message2']
   * 那再创建一个message的seed为2也就是 top = 70 * 2
  */
  props && (props.seed = instances.length);

  // 将实例，加入到instances中管理
  instances.push(instance);

  // 消息框出现
  if (props) {
    (props.isShow = true);
    (props.isEnter = true);
  }

  // 消息框离开
  setTimeout(() => {
    props && (props.isEnter = false);
    props && (props.isShow = false);
    props && (props.isLeave = true);
  }, props?.lastTime as number);

  // 移除消息框
  setTimeout(() => {
    close(props as any as IMessageOptions);
  }, props?.lastTime as number + 100);

}

// 关闭某个弹窗
const close = (props: IMessageOptions) => {
  // 移出第一个
  instances.shift();
  // 将每一个实例的seed减1, 因为移除了一个
  instances.forEach(v => v.component.props.seed -= 1);
  props.isDestory = true;
}
